using System;
using System.Collections.Generic;
using System.Threading;
namespace MicroMsg.Common.Utils
{
	public class WorkThread
	{
		public class JobParam
		{
			public Action doJob;
			public object arg1;
			public object arg2;
		}
		private AutoResetEvent workEvent = new AutoResetEvent(false);
		private List<WorkThread.JobParam> jobList;
		private static Thread thread;
		public WorkThread()
		{
			this.jobList = new List<WorkThread.JobParam>();
			WorkThread.thread = new Thread(new ParameterizedThreadStart(WorkThread.WorkThreadLoop));
			WorkThread.thread.set_Name("backGroundWorkThread");
			WorkThread.thread.set_IsBackground(true);
			WorkThread.thread.Start(this);
		}
		private WorkThread.JobParam getJob()
		{
			WorkThread.JobParam result;
			lock (this.jobList)
			{
				if (this.jobList.get_Count() <= 0)
				{
					return null;
				}
				result = this.jobList.get_Item(0);
				this.jobList.RemoveRange(0, 1);
			}
			return result;
		}
		private static void WorkThreadLoop(object parameter)
		{
			WorkThread workThread = parameter as WorkThread;
			while (true)
			{
				workThread.workEvent.WaitOne();
				WorkThread.JobParam job;
				while ((job = workThread.getJob()) != null)
				{
					job.doJob.Invoke();
				}
			}
		}
		public bool add_job(Action doJobAction)
		{
			if (doJobAction == null)
			{
				return false;
			}
			WorkThread.JobParam jobParam = new WorkThread.JobParam
			{
				doJob = doJobAction
			};
			lock (this.jobList)
			{
				this.jobList.Add(jobParam);
			}
			this.workEvent.Set();
			return true;
		}
	}
}
